<template>
  <view class="container">
    <view class="header">
      <!-- 编辑 -->
      <view class="edit-menu" @click="handleEditMenu">
        编辑
      </view>
      <!-- 添加菜谱 -->
      <view class="add-menu" @click="handleAddMenu">
        添加菜谱
      </view>
      <!-- 搜索 -->
      <view class="search-bar" @click="gotoSearchPage">
        <view class="search-input">搜索</view>
        <uni-icons type="search" size="18" color="#999" class="search-icon"></uni-icons>
      </view>
    </view>
    <!-- 左侧 -->
    <view class="main-content">
      <scroll-view class="category-list" scroll-y :scroll-top="categoryScrollTop">
        <view v-for="item in categories" :key="item.id" class="category-item"
          :class="{ active: currentCategory === item.id }" @click="switchCategory(item.id, true)">{{ item.name }}</view>
      </scroll-view>

      <!-- 右侧 -->
      <scroll-view class="product-list" scroll-y :scroll-with-animation="true" @scroll="handleProductScroll"
        :scroll-into-view="productScrollInto">
        <template v-for="item in categories" :key="item.id">
          <view :id="'category-' + item.id" v-if="hasProducts(item.id)" class="category-products"
            data-id="{{ item.categoryId }}">
            <view class="category-title">{{ item.name }}</view>
            <view class="product-item" v-for="item in getProductsByCategory(item.id)" :key="item.id">
              <view class="product-left" @click="gotoDetails(item.id)">
                <image v-if="item.image" :src="item.image" class="product-image" mode="aspectFill"></image>
                <view class="product-info">
                  <text class="product-name">{{ item.name }}</text>
                  <view class="product-sales">
                    <p>月销</p>
                    <uni-icons type="star-filled" size="10" v-if="true"></uni-icons>
                    <uni-icons type="star-filled" size="10" v-if="true"></uni-icons>
                    <uni-icons type="star-filled" size="10" v-if="true"></uni-icons>
                    <uni-icons type="star-filled" size="10" v-if="true"></uni-icons>
                    <uni-icons type="star-filled" size="10" v-if="true"></uni-icons>
                  </view>
                  <text class="product-price">{{ item.price }}</text>
                </view>
              </view>
              <view class="product-right">
                <view class="stepper">
                  <uni-icons v-if="getQuantityByCart(item) > 0" type="minus" size="20" @click="handleDecrease(item)" />
                  <p v-if="getQuantityByCart(item) > 0" class="count"> {{ getQuantityByCart(item) }}</p>
                  <uni-icons v-if="true" type="plus" size="20" @click="handleAdd(item)" class="add-btn"/>
                </view>
              </view>
            </view>
          </view>
        </template>
        <!-- 空状态 -->
        <view v-if="showEmpty" class="empty-tips">
          <image src="../../static/avatar.png" class="empty-image" />
          <text class="empty-text">{{ emptyText ? emptyText : '快去添加菜单吧～' }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 结算栏 -->
    <view class="checkout-bar">
      <view class="cart-info" @click="togglePanel">
        <text class="total-price-label">合计：</text>
        <text class="rmb-icon">¥</text>
        <text class="total-price">{{ cartTotal.price }}</text>
      </view>
      <button class="checkout-btn" @click="handleCheckout">去下单({{ cartTotal.num }})</button>
    </view>

    <!-- 购物车弹窗 -->
    <uni-popup ref="popup" type="bottom" :mask-click="true">
      <view class="popup-content">
        <text class="title">订单详情</text>
        <uni-icons type="trash" size="24"></uni-icons>
        <view v-for="item in items" :key="item.id">
          <view>{{ item.name }}</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive, computed, getCurrentInstance } from "vue";
import { useProductStore } from "../../stores/product";
import { useCartStore } from "../../stores/cart";

import { storeToRefs } from "pinia";
import { onShow } from "@dcloudio/uni-app";

const currentCategory = ref(1);
const categoryPositions = ref({});
const productScrollInto = ref("");
const categoryScrollTop = ref(0);
const animStyle = ref({});
const showShoppingCart = ref(false);
const currentProduct = ref(null);
const currentSpec = ref(0);
const isRotated = ref(false);
const popup = ref(null)
const showEmpty = ref(true);


const categoryTopRefs = ref([])
const productStore = useProductStore()

const cartStore = useCartStore();
const { cartTotal, items } = storeToRefs(cartStore);

const categoryTops = ref([])


// TODO: 获取分类列表
const categories = reactive([
  { id: 1, name: "小鸡招牌" },
  { id: 2, name: "香香肉菜" },
  { id: 3, name: "爽口时蔬" },
  { id: 4, name: "营养汤煲" },
  { id: 5, name: "主食面点" },
  { id: 6, name: "甜食点心" },
]);


onMounted(async () => {
  const instance = getCurrentInstance().proxy;
  const query = uni.createSelectorQuery().in(instance)
  query.selectAll('.category-products').boundingClientRect((data) => {
    categoryTops.value = data;
  }).exec();
  await productStore.fetchProducts()
})

onShow(() => {
  console.log(cartStore.items);

})

const productQuantities = computed(() => {
  const quantities = {};
  cartStore.items.forEach(item => {
    quantities[item.id] = item.quantity;
  })
  return quantities;
})

const gotoSearchPage = () => {
  uni.navigateTo({
    url: "/pages/menu/searchproduct",
  });
};

const handleEditMenu = () => {

};
const handleAddMenu = () => {
  uni.navigateTo({
    url: "/pages/menu/addproduct",
  });
};

const getQuantityByCart = (row) => {
  const target = cartStore.items.find((item) => item.id === row.id || 0);
  return target?.quantity > 0 ? target.quantity : undefined;
};
const switchCategory = (id, manual = false) => {
  currentCategory.value = Number(id);
  if (manual) {
    productScrollInto.value = `category-${id}`;
  }
};

const getProductsByCategory = (id) => {
  return productStore.products.filter((p) => p.categoryId === id);
};

const handleProductScroll = (e) => {
  const scrollTop = e.detail.scrollTop;
  const target = categoryTops.value.find((item) => {
    return item.top >= scrollTop + 56;
  });

  if (target) {
    switchCategory(target.id.split('category-')[1], false);
  }
};
const handleAdd = (product) => {
  cartStore.addItem(product);
};

const handleDecrease = (product) => {
  const currentProduct = cartStore.items.find((p) => p.id === product.id);
  if (currentProduct.quantity >= 0) {
    cartStore.deleteItem(product);
  }
}

const gotoPlaceOrder = () => {
  uni.navigateTo({
    url: "/pages/menu/placeorder",
  });
};

const hasProducts = (id) => {
  return getProductsByCategory(id).length > 0;
};

const gotoDetails = (productId) => {
  uni.navigateTo({
    url: `/pages/menu/details?id=${productId}`,
  });
}

const handleCheckout = () => {
  uni.navigateTo({
    url: "/pages/menu/placeorder",
  });
}

const togglePanel = () => {
  popup.value.open()
  isRotated.value = !isRotated.value
  showShoppingCart.value = !showShoppingCart.value
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background: #ffffff;
}

.edit-menu,
.add-menu {
  flex-shrink: 0;
  padding-right: 20px;
}

.search-bar {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 20px;
  padding: 8px 15px;
  margin-left: 15px;
}

.search-input {
  color: #999;
  margin-left: 8px;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.category-list {
  width: 200rpx;
  background-color: #f8f8f8;

  .category-item {
    padding: 30rpx 20rpx;
    font-size: 28rpx;
    text-align: center;
    border-left: 4rpx solid transparent;
    transition: all 0.2s;

    &.active {
      background-color: #fff;
      border-left-color: var(--primary-color);
      color: var(--primary-color);
      font-weight: bold;
    }
  }
}

.product-list {
  flex: 1;
  padding: 20rpx;

  .category-title {
    padding: 20rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    background-color: #f8f8f8;
  }

  .product-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    margin: 20rpx;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    .product-left {
      flex: 1;
      display: flex;
      align-items: center;
      min-width: 0;

      .product-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        flex-shrink: 0;
        margin-right: 24rpx;
      }

      .product-info {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 160rpx;

        .product-name {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          font-weight: bold;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
        }

        .product-sales {
          color: #999;
          font-size: 20rpx;
        }

        .product-price {
          font-size: 20rpx;
        }

      }
    }

    .product-right {
      position: relative;
      margin-top: 120rpx;
      width: 120rpx;

      .stepper {
        display: flex;
        align-items: center;
      }

      .count {
        min-width: 40rpx;
        text-align: center;
        font-size: 28rpx;
        color: #333;
      }

      .add-btn {
        position: absolute;
        right: 0;
      }
    }
  }
}

.empty-tips {
  text-align: center;
  padding: 100rpx 0;

  .empty-image {
    width: 300rpx;
    height: 300rpx;
    opacity: 0.6;
  }

  .empty-text {
    display: block;
    color: #999;
    font-size: 28rpx;
    margin-top: 30rpx;
  }
}

.anim-ball {
  position: fixed;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: var(--primary-color);
  z-index: 999;
  transition: all 0.6s cubic-bezier(0.4, 0.27, 0.8, 0.79);
  opacity: 0.8;
}

.spec-list {
  margin: 40rpx 0;

  .spec-item {
    display: inline-block;
    padding: 15rpx 30rpx;
    margin-right: 20rpx;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
    transition: all 0.2s;

    &.active {
      border-color: var(--primary-color);
      color: var(--primary-color);
      background: rgba(0, 168, 98, 0.1);
    }
  }
}

.add-cart-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: var(--primary-color);
  color: white;
  font-size: 32rpx;
  border-radius: 50rpx;
  margin-top: 40rpx;
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 999;

  .cart-info {
    display: flex;
    align-items: center;
    position: relative;

    .cart-icon {
      width: 50rpx;
      height: 50rpx;
      margin-right: 20rpx;
    }

    .cart-badge {
      position: absolute;
      right: -10rpx;
      top: -10rpx;
      min-width: 36rpx;
      height: 36rpx;
      line-height: 36rpx;
      color: white;
      border-radius: 18rpx;
      font-size: 24rpx;
      text-align: center;
      padding: 0 8rpx;
    }

    .total-num {
      font-size: 28rpx;
      color: #666;
      margin-right: 15rpx;
    }

    .total-price-label {
      font-size: 28rpx;
    }

    .rmb-icon {
      margin-right: 6rpx;
      font-size: 24rpx;
      color: var(--primary-color);
      font-weight: bold;
    }

    .total-price {
      font-size: 34rpx;
      color: var(--primary-color);
      font-weight: bold;
    }
  }

  .checkout-btn {
    background: var(--primary-color);
    color: white;
    height: 70rpx;
    line-height: 70rpx;
    padding: 0 50rpx;
    border-radius: 35rpx;
    font-size: 30rpx;
    margin: 0;

    &::after {
      border: none;
    }
  }

  :deep(.popup-content) {
    width: 100%;
    background-color: #fff;
    min-height: 60vh;
    /* 补充高度定义 */
    padding-bottom: env(safe-area-inset-bottom);
    /* 适配全面屏 */

    .item-image {
      width: 150rpx;
      height: 150rpx;
      border-radius: 30rpx;
    }
  }
}
</style>
